package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.system.service.IAppUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;

import java.util.HashSet;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements CustomUserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    private final ISysUserService userService;

    private final IAppUserService appUserService;

    private final SysPasswordService passwordService;

    private final SysPermissionService permissionService;

    public UserDetailsServiceImpl(ISysUserService userService, IAppUserService appUserService, SysPasswordService passwordService, SysPermissionService permissionService) {
        this.userService = userService;
        this.appUserService = appUserService;
        this.passwordService = passwordService;
        this.permissionService = permissionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);
        return createLoginUser(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username, String type) throws UsernameNotFoundException {
        if (StringUtils.equals(Constants.SYS_USER, type)) {
            return loadUserByUsername(username);
        } else if (StringUtils.equals(Constants.APP_USER, type)) {
            AppUser appUser = new AppUser();
            appUser.setLoginName(username);
            // 查询用户信息
            AppUser user = appUserService.selectAppUserList(appUser).stream().findFirst().orElse(null);
            if (StringUtils.isNull(user)) {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException("登录用户：" + username + " 不存在");
            } else if (user.getStatus() != null && user.getStatus() != 1) {
                log.info("登录用户：{} 已被停用.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            }
            return createLoginUser(user);
        } else {
            throw new ServiceException("错误的用户类型： " + type);
        }
    }

    public UserDetails createLoginUser(AppUser user) {
        return new LoginUser(user.getId(), Constants.APP_USER, user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, Constants.SYS_USER, permissionService.getMenuPermission(user));
    }
}